import { defineStore } from "pinia";
import { GetTenantInfo, LogOut } from "~/apis/api";
import { getUserInfo, updateUserInfo } from "~/apis/web";

interface DeptSimple {
  id: Number;
  name: String;
  parentId: Number;
}

interface PostSimple {
  id: Number;
  name: String;
}

interface RoleSimple {
  id: Number;
  name: String;
}
interface ProfileInfo {
  avatar: String;
  createTime: Number;
  dept?: DeptSimple;
  email: String;
  id: Number;
  loginDate: Number;
  loginIp: String;
  mobile: String;
  nickname: String;
  posts?: Array<PostSimple>;
  roles?: Array<RoleSimple>;
  sex: Number;
  username: Number;
}

interface ProfileRequestInfo {
  nickname?: String;
  email?: String;
  mobile?: String;
  sex?: Number;
  avatar?: String;
}

export const userStore = defineStore("userStore", {
  state: () => ({
    user: {
      id: "",
      bizUserId: "",
      username: "",
      email: "",
      avatar: "/favicon.ico",
    },
    token: "",
    tenantId: 184,
    profile: null as ProfileInfo | null,
  }),
  actions: {
    setUser(val: any) {
      this.user = val;
    },
    setToken(val: any) {
      useCookie("token").value = val;
      this.token = val;
    },
    setTenantId(val: any) {
      useCookie("tenantId").value = val;
      this.tenantId = val;
    },
    // 用户登录
    async loginAction(loginForm: any) {},
    // 获取用户信息
    async getUserInfoAction() {
      const { code, data } = await getUserInfo();
      if (code === 0) {
        this.profile = data;
      }
    },
    async updateUserInfoAction(payload: ProfileRequestInfo) {
      const { data, code } = await updateUserInfo(payload);
      if (code === 0 && data) {
        if (!this.profile) return;
        const validKeys = Object.keys(payload) as Array<
          keyof ProfileRequestInfo
        >;
        for (const key of validKeys) {
          const value = payload[key];
          if (value !== undefined) {
            this.profile[key] = value as keyof ProfileInfo extends typeof key
              ? ProfileInfo[typeof key]
              : never;
          }
        }
      }
    },
    // 用户退出
    async logoutAction() {
      LogOut().then((res) => {
        console.log("退出登录成功", res);
        this.user = {
          id: "",
          bizUserId: "",
          username: "",
          email: "",
          avatar: "/favicon.ico",
        };
        this.token = "";
        useCookie("token").value = "";
      });
    },
    // 用户退出
    async handleGetTenantInfo() {
      GetTenantInfo().then((res) => {
        console.log("租户信息", res);
      });
    },
  },
  persist: true,
});
